package com.siyuanren.gcocp.common.web.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.net.URLDecoder;

/**
 * Created by   guwr
 * Project_name education
 * Path         com.siyuanren.gcocp.common.web.controller.BaseController
 * Date         2017/3/13
 * Time         18:20
 * Description
 *
 * @author guwr
 */
public class BaseController implements Serializable {

    protected static final String TEXT_UTF8 = "text/html;charset=UTF-8";
    protected static final String JSON_UTF8 = "application/json;charset=UTF-8";
    protected static final String XML_UTF8 = "application/xml;charset=UTF-8";
    protected static final String LIST = "list";
    protected static final String VIEW = "view";
    protected static final String ADD = "add";
    protected static final String SAVE = "save";
    protected static final String EDIT = "edit";
    protected static final String UPDATE = "update";
    protected static final String DELETE = "delete";
    protected static final String PAGE = "page";
    protected static final String INDEX = "index";
    protected static final String SUCCESS = "success";
    protected static final String NONE = "none";
    protected static final String ERROR = "error";
    protected static final String INPUT = "input";
    protected static final String LOGIN = "login";
    protected static final String UTF_8 = "utf-8";
    protected static final String GBK = "GBK";
    private static final long serialVersionUID = -8283878224669185571L;
    private static Logger logger = LoggerFactory.getLogger(BaseController.class);
    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected HttpServletResponse response;

    /**
     * 根据参数名从HttpRequest中获取String类型的参数值，无值则返回"" .
     *
     * @param key .
     * @return String .
     */
    public String getString_UrlDecode_UTF8(String key) {
        try {
            return URLDecoder.decode(this.getString(key), UTF_8);
        } catch (Exception e) {
            return "";
        }
    }

    public String getString(String key) {
        return request.getParameter(key);
    }

    /**
     * 供AJAX返回使用(ajax的一种返回方式)
     *
     * @param msg
     */
    public void write(String msg) {
        PrintWriter write = null;
        try {
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            write = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        write.write(msg);
        write.close();
    }
}
